package com.xunyin.modules.coupon.rest;


import com.github.pagehelper.util.StringUtil;
import com.xunyin.api.XunyinException;
import com.xunyin.constant.Constants;
import com.xunyin.enums.StatusEnum;
import com.xunyin.modules.couponnew.domain.MtCouponGroup;
import com.xunyin.modules.couponnew.domain.MtUserCoupon;
import com.xunyin.modules.couponnew.service.CouponGroupService;
import com.xunyin.modules.couponnew.service.CouponService;
import com.xunyin.modules.couponnew.service.dto.GroupDataDto;
import com.xunyin.modules.couponnew.service.dto.GroupDataListDto;
import com.xunyin.modules.couponnew.service.dto.ReqCouponGroupDto;
import com.xunyin.modules.couponnew.service.mapper.MtUserCouponMapper;
import com.xunyin.pagination.PaginationRequest;
import com.xunyin.pagination.PaginationResponse;
import com.xunyin.utils.SecurityUtils;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 卡券分组管理类controller
 * <p>
 * Created by xunyinyunshang <3594419785@qq.com>
 * CopyRight 讯音云商 https://www.tonetn.com
 */
@Slf4j
@AllArgsConstructor
@Api(tags = "共享空间:卡券分组管理类")
@RestController
@RequestMapping("api/couponGroup")
public class BackendCouponGroupController {

    //private static final Logger logger = LoggerFactory.getLogger(BackendCouponGroupController.class);

    private final MtUserCouponMapper mtUserCouponMapper;

    /**
     * 卡券分组服务接口
     */
    private final CouponGroupService couponGroupService;

    /**
     * 卡券服务接口
     */
    private final CouponService couponService;


    //private final ExportService exportService;

    /**
     * 查询卡券分组列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseEntity<Map<String, Object>> list(HttpServletRequest request) {
        log.info("list");
        Integer page = request.getParameter("page") == null ? 1 : Integer.parseInt(request.getParameter("page"));
        Integer pageSize = request.getParameter("pageSize") == null ? Constants.PAGE_SIZE : Integer.parseInt(request.getParameter("pageSize"));
        String name = request.getParameter("name") == null ? "" : request.getParameter("name");
        String id = request.getParameter("id") == null ? "" : request.getParameter("id");
        String status = request.getParameter("status") == null ? StatusEnum.ENABLED.getKey() : request.getParameter("status");

        PaginationRequest paginationRequest = new PaginationRequest();
        paginationRequest.setCurrentPage(page);
        paginationRequest.setPageSize(pageSize);

        Map<String, Object> searchParams = new HashMap<>();
        if (StringUtil.isNotEmpty(name)) {
            searchParams.put("name", name);
        }
        if (StringUtil.isNotEmpty(id)) {
            searchParams.put("id", id);
        }
        if (StringUtil.isNotEmpty(status)) {
            searchParams.put("status", status);
        }

        paginationRequest.setSearchParams(searchParams);
        PaginationResponse<MtCouponGroup> paginationResponse = couponGroupService.queryCouponGroupListByPagination(paginationRequest);

        // 计算券种类、总价值
        if (paginationResponse.getContent().size() > 0) {
            for (int i = 0; i < paginationResponse.getContent().size(); i++) {
                MtCouponGroup object = paginationResponse.getContent().get(i);
                object.setMoney(couponGroupService.getCouponMoney(object.getId().intValue()));
                object.setNum(couponGroupService.getCouponNum(object.getId()));
            }
        }

        // 统计数据
        List<GroupDataListDto> groupData = new ArrayList<>();

        if (paginationResponse.getContent().size() > 0) {
            for (int i = 0; i < paginationResponse.getContent().size(); i++) {
                Integer groupId = paginationResponse.getContent().get(i).getId();
                GroupDataDto data = new GroupDataDto();
                data.setCancelNum(0);
                data.setExpireNum(0);
                data.setUseNum(0);
                data.setSendNum(0);
                data.setUnSendNum(0);
                GroupDataListDto item = new GroupDataListDto();
                if (null != data) {
                    item.setKey(groupId.toString());
                    item.setData(data);
                    groupData.add(item);
                }
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("paginationResponse", paginationResponse);
        result.put("groupData", groupData);

        return new ResponseEntity<>(result, HttpStatus.OK);

        // return getSuccessResult(result);
    }

    /**
     * 保存卡券分组信息
     *
     * @param request
     * @param reqCouponGroupDto
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @CrossOrigin
    public ResponseEntity save(HttpServletRequest request, @RequestBody ReqCouponGroupDto reqCouponGroupDto) {
/*        String token = request.getHeader("Access-Token");
        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }*/

        //reqCouponGroupDto.setOperator(accountInfo.getAccountName());

        if (reqCouponGroupDto.getId() != null && reqCouponGroupDto.getId() > 0) {
            couponGroupService.updateCouponGroup(reqCouponGroupDto);
        } else {
            couponGroupService.addCouponGroup(reqCouponGroupDto);
        }

        return new ResponseEntity(HttpStatus.OK);
        //return getSuccessResult(true);
    }

    /**
     * 删除卡券分组
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseEntity delete(HttpServletRequest request, @PathVariable("id") Integer id) {
/*        String token = request.getHeader("Access-Token");
        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }*/

        // 该分组已有数据，不允许删除
        Map<String, Object> searchParams = new HashMap<>();
        searchParams.put("GROUP_ID", id.toString());
        List<MtUserCoupon> dataList = mtUserCouponMapper.selectByMap(searchParams);
        if (dataList.size() > 0) {
            //return getFailureResult(201, "已发放卡券，不允许删除");
            throw new XunyinException("已发放卡券，不允许删除");
        }
        couponGroupService.deleteCouponGroup(id, SecurityUtils.getUsername());

        return new ResponseEntity(HttpStatus.OK);
        //return getSuccessResult(true);
    }

    /**
     * 更新状态
     *
     * @return
     */
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    @CrossOrigin
    public ResponseEntity updateStatus(HttpServletRequest request, @RequestBody Map<String, Object> params) {
/*        String token = request.getHeader("Access-Token");
        String status = params.get("status") != null ? params.get("status").toString() : StatusEnum.ENABLED.getKey();
        Integer id = params.get("id") == null ? 0 : Integer.parseInt(params.get("id").toString());

        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }*/
        String status = params.get("status") != null ? params.get("status").toString() : StatusEnum.ENABLED.getKey();
        Integer id = params.get("id") == null ? 0 : Integer.parseInt(params.get("id").toString());
        //try {
        //String operator = accountInfo.getAccountName();
        String operator = SecurityUtils.getUsername();
        ReqCouponGroupDto groupDto = new ReqCouponGroupDto();
        groupDto.setOperator(operator);
        groupDto.setId(id);
        groupDto.setStatus(status);
        couponGroupService.updateCouponGroup(groupDto);
        //} catch (BusinessCheckException e) {
        //    return getFailureResult(201, e.getMessage());
        //}
        return new ResponseEntity(HttpStatus.OK);
        //return getSuccessResult(true);
    }

    /**
     * 分组详情
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseEntity info(HttpServletRequest request, @PathVariable("id") Integer id) {
/*        String token = request.getHeader("Access-Token");
        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }*/

        MtCouponGroup mtCouponGroup = couponGroupService.queryCouponGroupById(id);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("groupInfo", mtCouponGroup);

        return new ResponseEntity(HttpStatus.OK);
        //return getSuccessResult(resultMap);
    }

    /**
     * 导出模板文件
     *
     * @param request
     * @param response
     */
/*    @RequestMapping(value = "/exportTemplate", method = RequestMethod.GET)
    @CrossOrigin
    public void exportTemplate(HttpServletRequest request, HttpServletResponse response) throws BusinessCheckException {
        ClassLoader classLoader = this.getClass().getClassLoader();
        URL url = classLoader.getResource("");
        String srcTemplateFilePath = url.getPath();

        ExcelExportDto excelExportDto = new ExcelExportDto();
        excelExportDto.setSrcPath(srcTemplateFilePath);
        excelExportDto.setSrcTemplateFileName("template" + File.separator + "importTemplate.xlsx");

        String filename = "批量发券模板" + ".xlsx";
        try {
            OutputStream out = response.getOutputStream();
            XlsUtil.setXlsHeader(request, response, filename);
            excelExportDto.setOut(out);
            exportService.exportLocalFile(excelExportDto);
        } catch (Exception e) {
            logger.error("导出出错", e);
            throw new BusinessCheckException("导出出错");
        }
    }*/

    /**
     * 上传文件
     *
     * @param request
     * @throws
     */
/*    @RequestMapping(value = "/upload/", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @CrossOrigin
    public ResponseObject uploadFile(HttpServletRequest request, @RequestParam("fileInput") MultipartFile file) {
        String token = request.getHeader("Access-Token");
        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }

        try {
            String filePath = couponGroupService.saveExcelFile(file, request);
            String uuid = couponGroupService.importSendCoupon(file, accountInfo.getAccountName(), filePath);
            return getSuccessResult(uuid);
        } catch (BusinessCheckException e) {
            return getFailureResult(201, e.getMessage());
        } catch (Exception e) {
            return getFailureResult(201, e.getMessage());
        }
    }*/

    /**
     * 查询分组列表
     */
    @RequestMapping(value = "/quickSearch", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseEntity<Map<String, Object>> quickSearch(HttpServletRequest request) {
/*        String token = request.getHeader("Access-Token");
        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }*/

        PaginationRequest paginationRequest = new PaginationRequest();
        paginationRequest.setCurrentPage(Constants.PAGE_NUMBER);
        paginationRequest.setPageSize(Constants.MAX_ROWS);
        paginationRequest.setSearchParams(new HashMap<>());
        PaginationResponse<MtCouponGroup> paginationResponse = couponGroupService.queryCouponGroupListByPagination(paginationRequest);

        List<MtCouponGroup> groupList = paginationResponse.getContent();

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("groupList", groupList);

        return new ResponseEntity<>(resultMap, HttpStatus.OK);
        //return getSuccessResult(resultMap);

    }
}
